<template>
	<view class="">
		<view class="page-bg-gray"></view>
		<view class="address-select-box">
			<view class="address-select-box-main" @click="selectAddress">
				<view class="address-info">
					<view class="address-selected" v-if="addressInfo.id">
						<view class="top">
							<view class="name">{{ addressInfo.addressee }}</view>
							<view class="phone">{{ addressInfo.mobile }}</view>
							<view class="tag">
								<text v-for="(item, index) in addressInfo.tag" :key="index" :class="{red:item.tagText=='默认'}">{{ item.tagText }}</text>
							</view>
						</view>
						<view class="bottom">
						{{ getAddressText(addressInfo) }}
						</view>
					</view>
					<view class="address-not" v-else>
						<u-icon name="map" size="46"></u-icon>
						<text class="text">选择收货地址</text>
					</view>
				</view>
				<view class="icon">
					<u-icon name="arrow-right" color="#CCC" size="36"></u-icon>
				</view>
				<!-- <view class="address-bg-img"></view> -->
			</view>
		</view>
		<view class="goods-box">
			<view class="order" v-for="(res, index) in orderList" :key="res.id">
				<view class="top">
					<view class="left">
						<u-icon name="home" :size="30" color="rgb(94,94,94)"></u-icon>
						<view class="store">{{ res.store_name }}</view>
					</view>
				</view>
				<view class="item-box" v-for="(item, gindex) in res.goodss" :key="gindex">
					<view class="item">
						<view class="left"><image :src="photoBaseUrl + item.cover" mode="aspectFill"></image></view>
						<view class="content">
							<view class="title u-line-2">{{ item.goods_name }}</view>
							<view class="type">{{ item.options[0].sku_name }}</view>
							<!-- <view class="delivery-time">发货时间 {{ item.deliveryTime }}</view> -->
						</view>
						<view class="right">
							<view class="price">
								￥{{ ((item.sell_price / 100)).toFixed(2) }}
							</view>
							<view class="number">x{{ item.buy_num }}</view>
						</view>
					</view>
					<view class="item item-bottom" v-if="item.discount_money > 0 || res.activity_discount_money > 0">
						<view class="left"></view>
						<view class="right price">每件到手价约 ￥{{ (item.paid / item.buy_num / 100).toFixed(2) }}</view>
					</view>
				</view>
				<u-cell-group :border="false">
					<u-cell-item title="商品合计" :arrow="false" :border-top="false" :border-bottom="false" hover-class="cell-hover-class" class="prices-cell-item">
						<view slot="right-icon" class="">
							<view class="prices-cell-item-right-icon">
								￥{{ (originalPrice(res) / 100).toFixed(2) }}
							</view>
						</view>
					</u-cell-item>
					<u-cell-item title="运费" :arrow="false" :border-top="false" :border-bottom="false" hover-class="cell-hover-class" class="prices-cell-item">
						<view slot="right-icon" class="">
							<view class="prices-cell-item-right-icon">
								￥{{freight}}
							</view>
						</view>
					</u-cell-item>
					<u-cell-item :arrow="false" :border-bottom="false" hover-class="cell-hover-class" 
					v-if="res.activity_discount_money > 0"
					class="prices-cell-item">
						<view slot="title" class="">
							立减
						</view>
						<view slot="right-icon" class="">
							<view class="prices-cell-item-right-icon">
								<view class="coupon-discount">-￥{{(res.activity_discount_money/100).toFixed(2)}}</view>
							</view>
						</view>
					</u-cell-item>
					<u-cell-item @click="gotoUseCoupon(index,res.group_id,res.mc_id,res.coupon_num)" :border-bottom="false" class="prices-cell-item">
						<view slot="title" class="">
							优惠券<text class="coupon-discount"
							v-if="selectCoupons.length > 0"
							>(已选{{selectCoupons.length}}张)</text>
						</view>
						<view slot="right-icon" class="">
							<view class="coupon-not" v-if="res.coupon_num < 1">无可用</view>
							<view class="coupon-select" 
							v-if="res.coupon_num > 0 && res.select_coupon_id < 1">{{ res.coupon_num }}张可用</view>
							<view class="coupon-discount" 
							v-if="res.select_coupon_id > 0">-￥{{(res.discount_money/100).toFixed(2)}}</view>
						</view>
					</u-cell-item>
					<u-cell-item title="发票" @click="gotoUseInvoice" :border-bottom="false" class="prices-cell-item">
						<view slot="right-icon" class="">
							不开发票
						</view>
					</u-cell-item>
					<u-cell-item :arrow="false" :border-bottom="false" hover-class="cell-hover-class" class="prices-cell-item">
						<view slot="right-icon" class="">
							共{{ totalNum(res.goodss) }}件 小计:<text class="price">￥{{itemGoodsTotalPrice(res,100)}}</text>
						</view>
					</u-cell-item>
				</u-cell-group>
			</view>
		</view>
		<view class="limit-tip-area-bottom" v-if="limitTip"></view>
		<view class="limit-tip" v-if="limitTip">
			{{ limitTip }}
		</view>
		<view class="order-create-tabbar-area-bottom"></view>
		<view class="order-create-tabbar">
			<view class="main">
				<view>
					共<text class="goods-num">{{goodsTotalNum()}}</text>件
				</view>
				<view class="paid-box" :class="discounts.length > 1 ? 'discount':''">
					<view class="info">
						合计:￥{{payable(100)}}
					</view>
					<view class="btn" @click="showCouponDetails">
						优惠减：￥40.00
						<u-icon custom-prefix="g-icon" name="shang" style="transform:scale(0.6,0.6)" size="10"></u-icon>
					</view>
				</view>
				<view class="right">
					<u-button type="error" size="medium" shape="circle"
					:hairLine="false" :loading="submitBtnLoading"
					@click="submitOrder" :disabled="limitTip.length > 0"
					>提交订单</u-button>
				</view>
			</view>
		</view>
		<u-popup mode="bottom" safe-area-inset-bottom v-model="couponDetails">
			<view class="detailsContent">
				<scroll-view scroll-y="true" style="height: 600rpx;">
					<view>
						<u-cell-group>
							<u-cell-item :arrow="false" title="商品总额">
								<view slot="right-icon" class="">
									￥ 100.00
								</view>
							</u-cell-item>
							<u-cell-item :arrow="false" title="活动:满200减20">
								<view slot="right-icon" class="discount-price">
									- ￥ 20.00
								</view>
							</u-cell-item>
							<u-cell-item :arrow="false" title="优惠券:满200减20">
								<view slot="right-icon" class="discount-price">
									- ￥ 20.00
								</view>
							</u-cell-item>
						</u-cell-group>
					</view>
				</scroll-view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default{
		computed: {
			// 价格小数
			priceDecimal() {
				return val => {
					if (val !== parseInt(val)) return val.slice(-2);
					else return '00';
				};
			},
			// 价格整数
			priceInt() {
				return val => {
					if (val !== parseInt(val)) return val.split('.')[0];
					else return val;
				};
			}
		},
		data() {
			return {
				queryData: {},
				addressInfo: {},
				couponList: [],
				photoBaseUrl: '',
				selectCoupons: [],
				selectMcIds: [], // 已经选择了的 MC id
				freight:0,
				submitBtnLoading: false,
				couponDetails: false,
				orderList: [],
				discounts: [],
				coupon_ids: [],
				messageId: '',
				checkSubmitOkTimer: null,
				limitTip: ''
			}
		},
		onLoad() {
			this.getCreateData(this.$Route.query)
		},
		methods:{
			selectAddress(){
				let that = this
				// 选择地址监听
				uni.$once('order-create-select-address',function(data){
					that.addressInfo = data
					// 赋值选择后的地址ID
					that.queryData.address_id = data.id
					that.getCreateData()
				})
				
				this.$myRouter.push({name:'order/select_address',params:{selected:this.addressInfo.id}})
			},
			checkQueryData(_query){
				let that = this
				if (_query.cart_data){
					_query = getApp().globalData.tmpSubmitData;
					if (!_query){
						uni.showModal({
							content:'参数错误，请重新提交',
							showCancel:false,
							success:function(res){
								that.$myRouter.back()
							}
						})
						return false
					}
					this.queryData = _query
				}
				if (_query.one_data){
					if(!_query.one_data.goods_id){
						this.$u.toast('goods_id 不能为空')
						return false
					}
					if(!_query.one_data.goods_num){
						this.$u.toast('goods_num 不能为空')
						return false
					}
					if(!_query.one_data.goods_option_id){
						this.$u.toast('goods_option_id 不能为空')
						return false
					}
					if (!_query.one_data.coupon_ids){
						_query.one_data.coupon_ids = []
					}
					this.queryData = _query
				}
				return true
			},
			getCreateData(_query){
				if(!this.checkQueryData(this.$Route.query)){
					return
				}
				this.getCreateDataByGoodsId()
			},
			getCreateDataByGoodsId(){
				const that = this
				uni.showLoading({
				    title: '加载中'
				});
				this.$api.order.create(this.queryData).then(res => {
					that.photoBaseUrl = res.photo_base_url
					that.orderList = res.order_groups
					that.discounts = res.discounts
					that.limitTip = res.goods_limit_tip
					if (res.address_info){
						that.addressInfo = res.address_info
					}
				}).catch(err => {
					uni.showModal({
						content:err.message,
						showCancel:false,
						success:function(res){
							that.$myRouter.back()
						}
					})
				}).finally(() => {
					uni.hideLoading();
				})
			},
			getCreateDataByCart(){
				
			},
			// 订单商品总计 - 数量
			goodsTotalNum(){ 
				let num = 0;
				this.orderList.map(order => {
					order.goodss.map(item => {
						num += item.buy_num
					})
				})
				return num;
			},
			// 订单商品总计 - 价格
			goodsTotalPrice(xiaoshu = 100){ 
				let price = 0;
				this.orderList.map(order => {
					price += this.itemGoodsTotalPrice(order,xiaoshu)
				})
				if (xiaoshu === 1){
					return price
				}
				return (price / xiaoshu).toFixed(2);
			},
			itemGoodsTotalPrice(item,xiaoshu = 100){
				let price = this.originalPrice(item);
				price -= item.discount_money
				price -= item.activity_discount_money
				if (xiaoshu === 1){
					return price
				}
				return (price / xiaoshu).toFixed(2);
			},
			originalPrice(item){
				let price = 0;
				item.goodss.map(item => {
					price += item.options[0].price * item.buy_num
				})
				return price;
			},
			// 应付
			payable(xiaoshu = 100){ 
				let totalPrice = this.goodsTotalPrice(1)
				// 要减掉优惠券等等
				return (totalPrice / xiaoshu).toFixed(2);
			},
			// 商店合计
			totalPrice(item) {
				let price = 0;
				item.map(val => {
					price += parseFloat(val.options[0].price * val.buy_num);
				});
				return (price / 100).toFixed(2);
			},
			// 商店合计总件数
			totalNum(item) {
				let num = 0;
				item.map(val => {
					num += val.buy_num;
				});
				return num;
			},
			getSubmitData(){
				let that = this
				// 检测是否选择地址
				if(!(that.addressInfo && that.addressInfo.id)){
					that.$u.toast('请选择收件地址')
					return
				}

				let submitData = JSON.parse(JSON.stringify(this.queryData))
				
				submitData.address_id = that.addressInfo.id
				
				return submitData;
			},
			submitOrder(){
				let that = this
				that.submitBtnLoading = true
				setTimeout(function() {
					that.submitBtnLoading = false
				}, 15000);
				let submitData = this.getSubmitData();
				// console.log(submitData);
				// return
				that.$api.order.submit(submitData).then(res => {
					// that.submitBtnLoading = false
					that.messageId = res.message_id
					// that.$myRouter.replace({name:'order/pay',params:{id:res.order_id}})
					that.checkSubmitOkTimer = setTimeout(that.checkSubmitOk,1000)
				}).catch(err => {
					that.submitBtnLoading = false
					that.$u.toast(err.message)
				})
			},
			checkSubmitOk(){
				let that = this
				this.$api.order.checkSubmitOk({message_id:this.messageId}).then(res => {
					clearTimeout(this.checkSubmitOkTimer)
					that.submitBtnLoading = false
					if (res.order_ids.length > 1){
						that.$u.toast('下单成功，多个订单请到订单列表进行支付')
						setTimeout(function() {
							that.$myRouter.replace({name:'member/order_list',params:{status:1}})
						}, 500);
					} else {
						that.$u.toast('下单成功')
						setTimeout(function() {
							that.$myRouter.replace({name:'order/pay',params:{id:res.order_ids[0]}})
						}, 500);
					}
					
				}).catch(err => {
					if (err.message !== 'reload'){
						this.submitBtnLoading = false
						this.$u.toast(err.message)
					}
					else {
						this.checkSubmitOkTimer = setTimeout(this.checkSubmitOk,1000)
					}
				})
			},
			gotoUseCoupon(_index,_group_id,_select_coupon_id,_coupon_num){
				if (_coupon_num < 1){
					// 没有可用的优惠券
					return
				}
				// 跳转到选择优惠券
				let that = this
				// 获取分组下的商品
				let qData = {
					selecteds: [],
					goods_list: [],
					no_selected: []
				}
				let goodsList = []
				that.orderList.map(order => {
					if (order.group_id == _group_id){
						order.goodss.map(item => {
							goodsList.push({
								goods_id:item.id,
								goods_option_id:item.options[0].id,
								goods_num:item.buy_num,
							})
						})
						qData.selecteds.push(order.mc_id)
					}
				})
				let tmpMcIds = []
				that.selectMcIds.map(rrr => {
					if (!qData.selecteds.includes(rrr)){
						tmpMcIds.push(rrr)
					}
				})
				qData.goods_list = goodsList
				qData.no_selected = tmpMcIds
				getApp().globalData.tmpUseCouponData = qData
				uni.$once("confirmUseCoupon",function(data){
					// 选择优惠券后回调
					if (that.queryData.cart_data){
						that.queryData.cart_data.map(cd => {
							if (cd.activity_id == _group_id){
								if (that.selectMcIds.includes(cd.coupon_ids[0])){
									that.selectMcIds.splice(that.selectMcIds.indexOf(cd.coupon_ids[0]),1)
								}
								cd.coupon_ids[0] = data.mc_id
								that.selectMcIds.push(data.mc_id)
							}
						})
					}
					if (that.queryData.one_data){
						that.queryData.one_data.coupon_ids[0] = data.mc_id
					}
					
					that.getCreateDataByGoodsId()
				})
				
				this.$myRouter.push({name:'order/use_coupon',params:{from:'order/create'}})
			},
			gotoUseInvoice(){
				this.$myRouter.push({name:'order/use_invoice',params:{good_ids:[1,2]}})
			},
			getAddressText(e){
				let texts = []
				let xunhuanNames = [
					'province',
					'city',
					'area',
					'street',
				]
				for	(var k in xunhuanNames){
					if('不显示' != e[xunhuanNames[k]]){
						texts.push(e[xunhuanNames[k]])
					}
				}
				return texts.join('-')
			},
			showCouponDetails(){
				this.couponDetails = true;
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import '@/static/css/member_order_list.scss';
	
	.address-select-box{
		// margin-top: 20rpx;
		position: relative;
		padding: 20rpx 20rpx 0 20rpx;
		.address-select-box-main{
			display: flex;
			background-color: #FFF;
			justify-content: space-between;
			border-radius: 20rpx;
		}
		.icon{
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: column;
			margin-right: 20rpx;
		}
	}
	.address-not{
		padding: 40rpx 40rpx;
		font-size: 36rpx;
		.text{
			margin-left: 10rpx;
		}
	}
	.address-bg-img {
		position: absolute;
		width: 100%;
		height: 8rpx;
		left: 0;
		bottom: 0;
		background: url("") repeat;
	}
	.address-selected {
		padding: 40rpx 40rpx;
		.top {
			display: flex;
			font-weight: bold;
			font-size: 34rpx;
			.phone {
				margin-left: 60rpx;
			}
			.tag {
				display: flex;
				font-weight: normal;
				align-items: center;
				text {
					display: block;
					width: 60rpx;
					height: 34rpx;
					line-height: 34rpx;
					color: #ffffff;
					font-size: 20rpx;
					border-radius: 6rpx;
					text-align: center;
					margin-left: 30rpx;
					background-color:rgb(49, 145, 253);
				}
				.red{
					background-color:red
				}
			}
		}
		.bottom {
			display: flex;
			margin-top: 20rpx;
			font-size: 28rpx;
			justify-content: space-between;
			color: #999999;
		}
	}
	.goods-box{
		.item-box{
			border-bottom: #EEE solid 1px;
			padding-bottom: 20rpx;
		}
	}
	.order-create-tabbar-area-bottom{
		height: 120rpx;
	}
	.order-create-tabbar{
		z-index: 100;
		border-top: 1px solid #CCC;
		background-color: #FFF;
		width: 100%;
		height: 100rpx;
		line-height: 100rpx;
		position: fixed;
		padding: 0 30rpx;
		bottom: 0;
		.main{
			position: relative;
			display: flex;
			font-size: 32rpx;
			.right{
				position: absolute;
				top:0;
				right: 0;
			}
			.goods-num{
				color: #000000;
				font-weight: 700;
			}
			.paid-box{
				margin-left: 10rpx;
				position: relative;
				min-width: 50%;
				.info{
					.price{
						font-size: 36rpx;
					}
				}
			}
			.paid-box.discount{
				.info{
					height: 72rpx;
					line-height: 72rpx;
				}
				.btn{
					position: absolute;bottom:0;color: #E41F19;height:60rpx;line-height:60rpx;
					font-size: 24rpx;
				}
			}
		}
	}
	.price{
		color: #E41F19;
		font-weight: 700;
	}
	.coupon-not{}
	.coupon-select{
		color: #333;
	}
	.coupon-discount{
		color: #E41F19;
	}
	.cell-hover-class{
		
	}
	.prices-cell-item{
		padding: 26rpx 0;
	}
	.prices-cell-item-right-icon{
		padding-right: 19px;
	}
	.other-box{
		margin: 20rpx;
		.group{
			border-radius: 20rpx;
			/deep/ .u-cell-item-box{
				border-radius: 20rpx;
			}
		}
	}
	.detailsContent{
		padding: 30rpx;
	}
	
	.discount-price{
		color: #E41F19;
	}
	.limit-tip-area-bottom{
		height: 100upx;
	}
	.limit-tip{
		position: fixed;
		bottom: 100upx;
		width: 100%;
		text-overflow:clip;
		background-color: #fdf6ec;
		border-top: 1px solid #fcbd71;
		padding: 0 20upx;
		line-height: 44upx;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
		display: -webkit-box;
		
	}
</style>